package com.jiang.user.controller;

import com.jiang.common.vo.Result;
import com.jiang.user.pojo.User;
import com.jiang.user.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(User param, @RequestParam("captcha") String captcha, HttpServletRequest request, HttpSession session) {

        if (!CaptchaUtil.ver(captcha, request)) {
            // 清除session中的验证码
            CaptchaUtil.clear(request);
            return Result.fail("验证码错误");
        }

        User user = userService.login(param);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //参数一是密码参数二是加密的值
        boolean matches = encoder.matches(param.getPassword(), user.getPassword());
        if (matches) {
            user.setPassword(null);
            session.setAttribute("userInfo",user);
            return Result.success();
        }
        return Result.fail("用户登陆失败");
    }

}
